package com.hjj.concurrence.research;

/**
 * <p>Threadlocal为每个线程提供局部变量</p>
 * <p>底层是一个map集合</p>
 *
 */
public class ThreadlocalTest {
    public static void main(String[] args) {
        Res res1 = new Res();
//        Res res2 = new Res();
        new Thread(new Thread01(res1)).start();
        new Thread(new Thread01(res1)).start();
    }
}

class Thread01 implements Runnable {

    private Res res;

    public Thread01(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + ", count:" + res.getNumber());
        }
    }
}

class Res {
//    private int count = 0;
//
//    public int getNumber() {
//        return count++;
//    }

    ThreadLocal<Integer> count = ThreadLocal.withInitial(() -> 0);

    public Integer getNumber() {
        Integer c = count.get() + 1;
        count.set(c);
        return c;
    }

}
